package net.nettytlv;

import net.nettytlv.domain.Packet;

import java.nio.ByteBuffer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Sharable
public class ServerChannelHandler extends SimpleChannelInboundHandler<Packet> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet packet) {
        log.debug(packet.toString());

        // 读取数据
        ByteBuf payload = Unpooled.copiedBuffer(packet.getValue());

        // 根据报文处理进行处理
        switch (packet.getType()) {
            case (byte) 1:
                int clientId = payload.readInt();
                log.debug("clientId= {}", clientId);
                ctx.writeAndFlush(PacketUtil.createPingAck(clientId));
                break;

            default:
                log.error("Not found type handler. type= {}", packet.getType());
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            log.debug("userEventTriggered id={}, idleStateEvent= {}", ctx.channel().id().toString(),
                    idleStateEvent.state());
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    ctx.close();
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
